using MeshExtend;
using System.Collections.Generic;
using UnityEngine;

public class SkillTreeUI_Line : MonoBehaviour
{
    private const float LineWidth = 4f;

    private SkillTreeUI_Manager manager;
    private MyImage myImage;

    private readonly Dictionary<Vector3, Vector3[]> points = new Dictionary<Vector3, Vector3[]>();

    private void Awake()
    {
        myImage = GetComponent<MyImage>();
    }

    private void Start()
    {
        manager = GetComponentInParent<SkillTreeUI_Manager>();
        GenerateLines();
    }

    private void GenerateLines()
    {
        Dictionary<SkillNode, SkillTreeUI_SkillNode> dict_node = new Dictionary<SkillNode, SkillTreeUI_SkillNode>();
        foreach (SkillTreeUI_SkillNode uiNode in manager.UINodes)
        {
            if (uiNode.skillNode == null)
                continue;
            dict_node.Add(uiNode.skillNode, uiNode);
        }
        foreach (SkillNode node in dict_node.Keys)
        {
            int length = node.unlockNodes.Length;
            if (length == 0)
                continue;
            Vector3[] tmp = new Vector3[length];
            int count = 0;
            foreach (var child in node.unlockNodes)
            {
                tmp[count++] = dict_node[child].GetComponent<RectTransform>().anchoredPosition;
            }
            AddLines(dict_node[node].GetComponent<RectTransform>().anchoredPosition, tmp);
        }
        Apply();
    }

    public void AddLines(Vector3 startPos, Vector3[] endPos)
    {
        points.Add(startPos, endPos);
    }

    public void Apply()
    {
        myImage.myMesh.Clear();
        foreach (Vector3 startPos in points.Keys)
        {
            foreach (Vector3 endPos in points[startPos])
            {
                Add_Polyline(startPos, endPos);
            }
        }
        myImage.Repaint();
    }

    private void Add_Polyline(Vector2 a, Vector2 b)
    {
        void AddLine(Vector2 a, Vector2 b)
        {
            myImage.myMesh.AddLine(a, b, LineWidth, true);
        }

        float mid = (a.y + b.y) / 2;
        Vector2 amid = new Vector2(a.x, mid);
        Vector2 bmid = new Vector2(b.x, mid);
        AddLine(a, amid);
        AddLine(amid, bmid);
        AddLine(bmid, b);
    }
}